"use client"

import { useState, useEffect, useMemo } from "react"
import { Dashboard } from "@/components/dashboard"
import DataCollection from "@/components/data-collection"
import { DataManagement } from "@/components/data-management"
import { KnowledgeBase } from "@/components/knowledge-base"
import { AiChat } from "@/components/ai-chat"
import ProjectManagement from "@/components/project-management"
import { Header } from "@/components/header"
import { AuthPage } from "@/components/auth-page"
import { useAuth } from "@/hooks/useAuth"
import { User } from "@/types/auth"
import { DataRecord, DataType } from "@/types/taskdata"

interface ExperimentData {
  id: number
  experimentName: string
  cropType: string
  customCrop?: string
  collector: string
  location: string
  date: string
  temperature: string
  humidity: string
  soilMoisture: string
  lightIntensity: string
  notes: string
  files: File[]
  status: string
  createdAt: string
}



/**
 * 主页组件 - 智慧农业实验数据管理系统
 * 
 * 功能特性：
 * 1. 支持两种用户类型：实验室和实验室成员
 * 2. 根据用户类型显示不同的导航菜单
 * 3. 实验室用户可以访问项目管理功能
 * 4. 实验室成员只能访问基本的数据管理功能
 */
export default function HomePage() {
  const [activeSection, setActiveSection] = useState("dashboard")
  const [experimentData, setExperimentData] = useState<ExperimentData[]>([])
  const [dataRecords, setDataRecords] = useState<DataRecord[]>([])
  const { user, isAuthenticated, isLoading, logout } = useAuth()

  // 计算数据类型统计
  const dataTypeStats = useMemo(() => {
    const typeMap = new Map<DataType, number>()
    const colorMap: Record<DataType, string> = {
      spectral: "bg-purple-500",
      image: "bg-blue-500", 
      sensor: "bg-green-500",
      weather: "bg-orange-500",
      soil: "bg-yellow-500",
      disease: "bg-red-500",
      yield: "bg-indigo-500",
      others: "bg-gray-500"
    }
    
    const labelMap: Record<DataType, string> = {
      spectral: "光谱数据",
      image: "图像数据",
      sensor: "传感器数据",
      weather: "气象数据",
      soil: "土壤数据",
      disease: "病虫害数据",
      yield: "产量数据",
      others: "其他数据"
    }

    dataRecords.forEach(record => {
      typeMap.set(record.type, (typeMap.get(record.type) || 0) + 1)
    })

    return Array.from(typeMap.entries()).map(([type, count]) => ({
      type: labelMap[type],
      count,
      color: colorMap[type]
    }))
  }, [dataRecords])

  // 监听认证状态变化，在用户登录成功后显示主界面
  useEffect(() => {
    console.log('状态变化检测:', { 
      isAuthenticated, 
      user: user?.email, 
      isLoading, 
      activeSection 
    })
    
    // 只要认证成功且有用户信息，立即跳转
    if (isAuthenticated && user && !isLoading) {
      const userTypeText = user.user_type === 'laboratory' ? '实验室管理员' : '实验室成员'
      console.log(`欢迎 ${userTypeText} ${user.full_name || user.username} 登录系统！切换到dashboard`)
      
      // 强制设置为dashboard
      if (activeSection !== "dashboard") {
        setActiveSection("dashboard")
      }
    }
  }, [isAuthenticated, user, isLoading]) // 只监听这些关键状态

  const handleLogout = async () => {
    await logout()
    setActiveSection("dashboard")
  }

  // 处理导航切换，现在所有用户类型都可以访问项目管理
  const handleSectionChange = (section: string) => {
    // 已移除对实验室成员访问项目管理的限制
    setActiveSection(section)
  }



  const addExperimentData = (data: Omit<ExperimentData, "id" | "status" | "createdAt">) => {
    const newData: ExperimentData = {
      ...data,
      id: Date.now(),
      status: "已完成",
      createdAt: new Date().toISOString(),
    }
    setExperimentData((prev) => [newData, ...prev])
    
    // 同时添加到数据记录
    const dataRecord: DataRecord = {
      id: `data-${Date.now()}`,
      project_id: "default-project",
      name: data.experimentName,
      description: data.notes || "无描述",
      type: "sensor", // 默认类型，可以根据实际情况调整
      location: data.location,
      collection_date: data.date,
      owner: data.collector,
      crop_type: data.cropType === "other" ? data.customCrop : data.cropType,
      attachments: data.files.map((file, index) => ({
        id: `file-${Date.now()}-${index}`,
        filename: file.name,
        file_type: file.type,
        size: file.size,
        path: `uploads/${file.name}`,
        uploaded_at: new Date().toISOString()
      })),
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString()
    }
    setDataRecords((prev) => [dataRecord, ...prev])
  }

  // 如果正在检查认证状态，显示加载界面
  if (isLoading) {
    console.log('显示加载界面 - isLoading:', isLoading)
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="text-center space-y-4">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto"></div>
          <p className="text-muted-foreground">正在加载...</p>
        </div>
      </div>
    )
  }

  // 如果用户未登录，显示登录页面
  if (!isAuthenticated || !user) {
    console.log('显示登录页面 - isAuthenticated:', isAuthenticated, 'user:', !!user)
    return <AuthPage />
  }

  console.log('显示主界面 - activeSection:', activeSection)

  const renderContent = () => {
    switch (activeSection) {
      case "dashboard":
        return <Dashboard experimentData={experimentData} />
      case "project-management":
        return <ProjectManagement />
      case "collection":
        return <DataCollection 
          onDataSubmit={addExperimentData} 
          recentRecords={dataRecords}
          dataTypeStats={dataTypeStats}
        />
      case "management":
        return <DataManagement experimentData={experimentData} />
      case "knowledge":
        return <KnowledgeBase />
      case "ai-chat":
        return <AiChat />
      default:
        return <Dashboard experimentData={experimentData} />
    }
  }

  return (
    <div className="min-h-screen bg-background">
      <Header 
        activeSection={activeSection} 
        onSectionChange={handleSectionChange}
        user={user}
        onLogout={handleLogout}
      />
      <main className="p-6 pl-20 pt-20">{renderContent()}</main>
    </div>
  )
}
